//
//  LCHomeTableViewController.m
//  wan77
//
//  Created by jiukuyinyue on 2017/8/17.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCHomeTableViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "LCHorizontalGrideView.h"
#import "SDCycleScrollView.h"
#import "NetworkTool.h"
#import <YYModel/YYModel.h>
#import <WebKit/WKWebView.h>
#import "BeautifulEssayModel.h"
#import "LCAccountManager.h"
#import "LCHtmlController.h"
#import "LCEssayTableViewCell.h"
#import "LCHomeEssayRightImageTableViewCell.h"
#import "LCHomeEssayImagesTableViewCell.h"
#import "LCHomeEssayVideoTableViewCell.h"


#import "LCVideoHtmlDetailsController.h"
#import "LCHomeTableViewController+LoadData.h"

#import "UIViewController+LCHidden.h"

#define LCEssayCell @"LCEssayCellIdentifier"
#define LCEssayImagesCell @"LCEssayImagesCellIdentifier"
#define LCEssayVideoCell @"LCEssayVideoCellIdentifier"

@interface LCHomeTableViewController ()
<SDCycleScrollViewDelegate,LCHorizontalGrideViewDataSource,LCHorizontalGrideViewDelegate>

///中间原项目按钮
@property (strong,nonatomic) LCHorizontalGrideView  *horizontalGrideView;

@property (assign,  nonatomic) bool isPop;

@end

@implementation LCHomeTableViewController
{
    NSArray<LCCycleModel *> *_beforeArray;
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    //设置代理即可
//    self.navigationController.delegate = self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _lastDate = [[NSDate alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyTabBarDoubleClick:) name:NOTIFY_TABBAR_DOUBLE_CLICK object:nil];
    _listPageNum = 1;
    _beautifulEssayListArray = [NSMutableArray array];
    [self setupUI];
    [self setupAddFloatingButtonToSuperview:self.view];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
///增加文章
- (void)setupAddFloatingButtonToSuperview:(UIView *)view {
    UIButton *bgButton = [[UIButton alloc] init];
    [view addSubview:bgButton];
//    [view bringSubviewToFront:bgButton];
    UIButton *addFloatingButton = [[UIButton alloc] init];
    [addFloatingButton setBackgroundImage:[UIImage imageNamed:@"首页编辑"] forState:UIControlStateNormal];
    [addFloatingButton addTarget:self action:@selector(addFloatingButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [bgButton addSubview:addFloatingButton];
    [addFloatingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-16);
        if (@available(iOS 11, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-16);
        } else {
            make.bottom.equalTo(self.view.mas_bottom).offset(-16);
        }
        make.width.height.mas_equalTo(50);
    }];
    [bgButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(addFloatingButton);
        make.left.top.equalTo(addFloatingButton).offset(3);
        make.right.bottom.equalTo(addFloatingButton).offset(-3);
    }];
    bgButton.backgroundColor = [UIColor whiteColor];//bai色
    [bgButton setRadius:25-1.5];
}
///增加文章
- (void)addFloatingButtonClick:(UIButton *)send {
    [self clickAlertCreateWenHtmlVC];
}
- (void)clickAlertCreateWenHtmlVC {
    if([[_UserM usercode] isEqualToString:@""]){
        pushAccLoginVC;
        return;
    }
    NSString *clzName = @"LCCreateWenHtmlVC";
    Class clz = NSClassFromString(clzName);
    LCViewController *viewController = [[clz alloc] init];
    viewController.vcInitDictData = [NSDictionary dictionaryWithObjectsAndKeys:@"添加文章", @"title",
                                     [NSString stringWithFormat:@"http://fuyin-admin.app.inping.com/home/edit/ad?usercode=%@",[_UserM usercode]], @"link", @"我的文章", @"rightTitle", nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

-(void)setupUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.right.bottom.equalTo(self.view);
    }];

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];

    [self.tableView registerNib:[UINib nibWithNibName:@"LCEssayTableViewCell" bundle:nil] forCellReuseIdentifier:LCEssayCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LCHomeEssayImagesCell" bundle:nil] forCellReuseIdentifier:LCEssayImagesCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LCHomeEssayVideoCell" bundle:nil] forCellReuseIdentifier:LCEssayVideoCell];
    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 10, 0, 10)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = RGBColor(236, 236, 236);
    //头部视图
    [self setupHeaderView];
    [self setupCycleScrollView];
    [self loadCycleScrollViewData];
    [self loadDataWithPage:NO];
    [self hideTheKeyboard];
}

//隐藏键盘Hide the keyboard
-(void)hideTheKeyboard{
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}

// 图片轮播器
-(void)setupCycleScrollView{
    if(_cycleScrollView == nil) {
        _cycleScrollView = [SDCycleScrollView new];
        _cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeholder"];
        _cycleScrollView.delegate = self;
        _cycleScrollView.currentPageDotColor = [UIColor redColor];
        
        _cycleScrollView.autoScrollTimeInterval = 5;// 自动滚动时间间隔
//        [_cycleScrollView.layer setMasksToBounds:YES];
//        [_cycleScrollView.layer setCornerRadius:4];
    }
}


- (void)setupHeaderView{
    [self setupCycleScrollView];//创建轮播图
    CGFloat height = 160;
    height = [LCUtils picValueToFitValueForNum:160.0f];
    UIView *headerView = [[UIView alloc] init];
    // 0    35
    self.cycleScrollView.frame = CGRectMake(0, 0, self.view.bounds.size.width, height);
    
    [headerView addSubview:self.cycleScrollView];
    
    CGFloat horizontalHeight = 0;
    horizontalHeight = [LCUtils picValueToFitValueForNum:98];
//    if (ScreenWidth == 320) {
//        horizontalHeight = 80;
//    }else if ((ScreenWidth == 375)){
//        horizontalHeight = 98;
//    }
//    else{
//        horizontalHeight = 110;
//    }
    self.horizontalGrideView.frame = CGRectMake(0, CGRectGetMaxY(self.cycleScrollView.frame), self.view.bounds.size.width, 120 + horizontalHeight);
    self.horizontalGrideView.backgroundColor = [UIColor whiteColor];

    [headerView addSubview:self.horizontalGrideView];
    
    headerView.frame =  CGRectMake(0, 0, self.view.bounds.size.width, CGRectGetMaxY(self.horizontalGrideView.frame));//
    
    self.tableView.tableHeaderView = headerView;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;//就可以正常
    
    //添加以下代码关闭估算行高
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;

    [self setupMJRefresh];
}
#pragma mark -  下拉刷新 上拉加载更多  -
- (void)setupMJRefresh {
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshGifHeader *refreshGifHeader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 隐藏时间
    refreshGifHeader.lastUpdatedTimeLabel.hidden = YES;
    // 设置header
    self.tableView.mj_header = refreshGifHeader;
    // 上拉刷新
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadDataWithPage:YES];//加载更多数据,翻页, 刷新UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.tableView.mj_footer endRefreshing];
        });
    }];
}
-(void)loadNewData{
    [self loadDataWithPage:NO];//加载数据, 刷新UI
}

-(void)notifyTabBarDoubleClick:(NSNotification *)noti{
    NSDate *date = [[NSDate alloc] init];
    if (date.timeIntervalSince1970 - _lastDate.timeIntervalSince1970 > 1) {
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
        _lastDate = date;
    }
}
#pragma mark - UITableView data source -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
#pragma mark - 设置区头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return  10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.beautifulEssayListArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier;
    BeautifulEssayModel *model = self.beautifulEssayListArray[indexPath.row];
    //多张图片
    if (model.cover.count > 2) {
        LCHomeEssayImagesTableViewCell *cell;
        cellIdentifier = LCEssayImagesCell;
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[LCHomeEssayImagesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else{
        //文章
        if ([model.type isEqualToString:@"3"]) {
            LCHomeEssayRightImageTableViewCell *cell;
            cellIdentifier = LCEssayCell;
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (!cell) {
                cell = [[LCHomeEssayRightImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            cell.model = model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            //视频样式
            LCHomeEssayVideoTableViewCell *cell;
            cellIdentifier = LCEssayVideoCell;
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (!cell) {
                cell = [[LCHomeEssayVideoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            cell.model = model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BeautifulEssayModel *model;
    if (self.beautifulEssayListArray.count > indexPath.row) {
        model = self.beautifulEssayListArray[indexPath.row];
    }
    NSLog(@"model.remoteUrl = %@", model.remoteUrl);
    if ([model.type isEqualToString:@"0"]) {//  0.广告
        return;
    }
    [LSZSpecialPackaging increaseTheNumberOfViews:model.id :^(BOOL isOK) {
        if (isOK == YES) {

        }
    }];
    if ([model.type isEqualToString:@"1"] || [model.type isEqualToString:@"2"]) {//1. 音频   2.视频
        LCVideoWebViewController *viewController = [[LCVideoWebViewController alloc] init];
        viewController.link = model.remoteUrl;
        viewController.model = model;
        viewController.beautifulEssayListArray = self.beautifulEssayListArray;
        [self.navigationController pushViewController:viewController animated:YES];
        return;
    }
    LCWenHTMLViewController *viewController = [[LCWenHTMLViewController alloc] init];
    viewController.link = model.remoteUrl;
    viewController.model = model;
    viewController.beautifulEssayListArray = self.beautifulEssayListArray;
    [self.navigationController pushViewController:viewController animated:YES];

}

#pragma mark -  SDCycleScrollView Delegate  -
#pragma mark - 轮播图的点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
//    __weak typeof(self) weakSelf = self;
    if (self.cycleArray.count >0) {
        LCCycleModel *cycleDict =  self.cycleArray[index];
        NSString * url = cycleDict.url;
        if (_pushVCBlock != nil) {
            if ( cycleDict.url == nil || cycleDict.type == nil || [cycleDict.url isEqualToString:@""] || [cycleDict.type isEqualToString:@""]) {
                return;
            }
            if ([cycleDict.type isEqualToString:@"1"] || [cycleDict.type isEqualToString:@"2"]) {
                _pushVCBlock(@[url,cycleDict.type]);// 1.捐赠 2.电商
                return;
            }
            _pushVCBlock(@[url,cycleDict.type]);// 0 文章 视频
            
        }
    }else{
        return;
    }
}
#pragma mark -  UITableViewDelegate  -
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BeautifulEssayModel *model = self.beautifulEssayListArray[indexPath.row];
    if ([model.type isEqualToString:@"0"]) {
        if (ScreenWidth == 320) {
            return 86.5;
        }
        else if (ScreenWidth == 375) {
            return 98;
        }
        else if (ScreenWidth == 414) {
            return 106;
        }
    }
    if (model.cover.count > 2) {
        if (ScreenWidth == 320) {
            return 161;
        }
        else if (ScreenWidth == 375) {
            return 174.5;
        }
        else if (ScreenWidth == 414) {
            return 184;
        }
    }
    
    if ([model.type isEqualToString:@"3"]) {
        if (ScreenWidth == 320) {
            return 86.5;
        }
        else if (ScreenWidth == 375) {
            return 98;
        }
        else if (ScreenWidth == 414) {
            return 106;
        }
    }
    
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:[UIScreen mainScreen].bounds.size.width tableView:tableView];
}
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
#pragma mark - LCHorizontalGrideViewDataSource -
-(LCHorizontalGrideView *)horizontalGrideView{
    if (_horizontalGrideView == nil) {
        _horizontalGrideView = [[LCHorizontalGrideView alloc] init];
        _horizontalGrideView.delegate = self;
        _horizontalGrideView.dataSource = self;
        _beforeArray = [NSArray lc_arrayWithPlist:@"homeButton.plist" andClassName:@"LCCycleModel"];
//  @[@"圣经阅读",@"赞美诗歌",@"每日灵修",@"诗歌歌谱",@"牧师讲道",@"祷告见证",@"每日美文",@"发现更多"];
        [_horizontalGrideView reloadData];
    }
    return _horizontalGrideView;
}

/**
 提供数据的数量
 
 @param horizontalGrideView 控件本身
 @return 返回数量
 */
- (NSInteger)numberOfItemsInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 8;
}


/**
 提供选项标题
 
 @param horizontalGrideView 当前控件
 @param index 选项下标
 @return 返回标题
 */
- (NSString *)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView titleForItemAtIndex:(NSInteger)index {
    return [NSString stringWithFormat:@"%@",_beforeArray[index].title];
}


/**
 提供选项的图标地址路径
 
 @param horizontalGrideView 当前控件
 @param index 选项下标
 @return 返回图标路径
 */
- (NSString *)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView iconURLForItemAtIndex:(NSInteger)index {
    return [NSString stringWithFormat:@"%@",_beforeArray[index].imgsrc];
}

#pragma mark - LCHorizontalGrideViewDelegate -

- (NSInteger)numberOfRowsPerPageInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 2;
}

- (NSInteger)numberOfColumnsPerPageInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 4;
}
#pragma mark - 中间按钮点击事件 -
-(void)pushVCWithClzName:(NSString *)clzName comeFromVC:(UIViewController *)vc{
    Class clz = NSClassFromString(clzName);//将字符串转化成class
    UIViewController *viewController = [[clz alloc] init];
    [vc.navigationController pushViewController:viewController animated:YES];
}
/**
 当选项被点击回调
 
 @param horizontalGrideView 当前控件
 @param index 点击下标
 */
- (void)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView didSelectItemAtIndex:(NSInteger)index {
        //点击方
        if (_pushVCBlock != nil) {
            if (index==1 ) {
                _pushVCBlock(@[@"1"]);//赞美诗歌
                return;
            }
            else if (index == 3) {
                _pushVCBlock(@[@"4"]);//了解基督
                return;
            }
           else if (index ==5) {
                _pushVCBlock(@[@"5"]);//牧师讲道
                return;
            }
           else if (index == 7) {
               _pushVCBlock(@[@"7"]);//发现更多
               return;
           }
           else if (index == 4) {
               [self pushVCWithClzName:@"LCBeautifulEssayListTableViewController" comeFromVC:self];
                return;
            }
            else{
                _pushVCBlock(@[_beforeArray[index].vc]);

            }
        }
}

/**
 返回当前选中的pageControl 颜色
 
 @param horizontalGrideView 当前控件
 @return 颜色
 */
- (UIColor *)colorForCurrentPageControlInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return [UIColor clearColor];
}


@end
